<?php
/**
 *
 *
 *
 */
class Yz_Form_Element_Date
    extends Yz_Form_Element_Abstract
    implements Yz_Form_Element_Interface
{

    protected $name;
    protected $exception;
    protected $value;

    public function render(Yz_Template_Interface $template)
    {
        debug();
        $class = $this->getCSSClass();
        $dateValue = Yz_Date::valueOf($this->value);
        $date = new Yz_Date($dateValue);
        $elemId = $class . '-' . $this->name;
        $this->includeJS($template, $date, $elemId);
        $o = <<<html
            <input type="text" name="{$this->name}" id="{$elemId}" value="{$date}" class="{$class}" size="10" />\n
html;
        return $o;
    }


    public function parse(Yz_Hash $values)
    {
        $elName = $this->name;
        if (! $values->offsetExists($elName)) {
            throw new Yz_Form_Element_Exception("Missing value for element {$elName}");
        }
        $value = $values[$elName];
        debug("Element '$elName', value '$value'");
        if ("" === $value) {
            $this->value = $this->getDefaultValue();
        } else {
            try {
                $val = new Yz_Date($value);
                $this->value = (string)$val;
            } catch (Yz_Exception $dex) {
                debug($dex);
                $ex = new Yz_Form_Element_Exception;
                $this->exception = $ex->withArgs(array('name' => $elName));
                throw $ex;
            }
        }
        return $this;
    }


    protected function getDefaultValue()
    {
        return "";
    }


    protected function includeJS($template, $date, $elemId)
    {
        if ($date->isEmpty()) {
            $date = Yz_Date::fromTimestamp(YZ_TIME);
        }
        $y = $date->getYear();
        $m = $date->getMonth();
        $d = $date->getDay();
        $webRoot = $template->webRoot;
        $js = <<<js
$( function() {
    $("#{$elemId}").datepicker( {
        defaultDate: new Date({$y}, {$m}-1, {$d}), // NOTE: months start from 0
        changeYear: true
    });
});
js;

        // TODO choose correct language
        $lang = 'ru';
        $template->includeJS($template::JQUERY_UI_JS);
        $template->includeCSS($template::JQUERY_UI_CSS);
        $template->includeJS("./www/jquery/datepicker-i18n/{$lang}.js");
        $template->includeJS('datepicker', $js);
        return $this;
    }

}
